// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment");

cloud.init()


function isTimeRange(beginTime, endTime) {
  var strb = beginTime.split(":");
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split(":");
  if (stre.length != 2) {
    return false;
  }

  var b = new Date()
  var e = new Date();
  var n = new Date();
  n.setHours(n.getHours() + 8);
  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);

  console.log("beginHour:" + b.getHours());
  console.log("nowHour:" + n.getHours());
  console.log("endHour:" + e.getHours());
  if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
    return true;
  } else {
    return false;
  }
}
//是否星期天
function isSunDay() {
  var dt = new Date()
  dt.setHours(new Date().getHours() + 8);
  if (dt.getDay() == 0) {
    //0--sunday, 6--saturday
    return true;
  } else {
    return false;
  }
}

//是否星期一
function isMonDay() {
  var dt = new Date()
  dt.setHours(new Date().getHours() + 8);
  console.log("getDay:" + dt.getDay());
  if (dt.getDay() == 1) {
    //0--sunday, 6--saturday
    return true;
  } else {
    return false;
  }
}

//是否是每月的最后一天的最后一小时
function isLastDayTimeRange() {
  console.log('isLastDayTimeRange()', moment().add(8, 'hours').format('lll'))
  moment.locale('zh-cn');
  let now = moment().add(8, 'hours').valueOf();
  console.log('now', now)
  let beginTime = moment().endOf('month').subtract(1, 'hours').valueOf();
  console.log('beginTime', beginTime)
  let endTime = moment().endOf('month').add(12, "hours").valueOf();
  console.log('endTime', endTime)
  if (now >= beginTime && now <= endTime) {
    return true;
  } else {
    return false;
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  //如果在星期天的23.00 - 23.59 不让打卡
  console.log('isSunDay:' + isSunDay())
  console.log('isTimeRange:' + isTimeRange('23:00', '23:59'))
  if (isSunDay() && isTimeRange('23:00', '23:59')) {
    return {
      success: false,
      message: "积分统计中，星期天23.00到第二天12:00不能打卡哦~",
    }
  }
  console.log('isMonDay:' + isMonDay())
  console.log('isTimeRange:' + isTimeRange('00:00', '12:00'))
  if (isMonDay() && isTimeRange('00:00', '12:00')) {
    return {
      success: false,
      message: "积分统计中，星期天23.00到第二天12:00不能打卡哦~",
    }
  }

  if (isLastDayTimeRange()) {
    return {
      success: false,
      message: "积分统计中，每个月的最后一天23.00到第二天12:00不能打卡哦~",
    }
  }

  const wxContext = cloud.getWXContext()
  let {
    OPENID,
    APPID,
    UNIONID
  } = wxContext
  let {
    userInfo,
    type,
    distance,
    time,
    speed,
    message,
    level,
    ropeNo,
    heartrate,
    calorie,
    altitude,
    images,
    status,
    isRace,
    isActivity
  } = event
  const db = cloud.database()
  var id = ''
  moment.locale('zh-cn');
  date = moment().add(8, 'hours').format('lll');
  systemTime = moment().valueOf();
  var user = await db.collection('user').where({
    _openid: OPENID
  }).get()

  if (user.data.length == 0) {
    return {
      success: false,
      message: "你还未登录哦，请先登录再打卡！",
    }
  }

  if (!user.data[0].isMember) {
    return {
      success: false,
      message: "你还不是川行者的会员，请联系教练审批。",
    }
  }
  var rules = await db.collection('rules').where({
    team: user.data[0].team
  }).get()
  var card = {
    _openid: OPENID,
    type: type,
    distance: distance,
    time: time,
    speed: speed,
    message: message,
    level: level,
    ropeNo: ropeNo,
    heartrate: heartrate,
    calorie: calorie,
    images: images,
    status: status,
    date: date,
    systemTime: systemTime,
    point: 0,
    altitude: altitude,
    isRace: isRace,
    isActivity: isActivity,
    userInfo: {
      avatarUrl: userInfo.avatarUrl,
      nickName: userInfo.nickName
    }
  }

  var m = moment().utcOffset(480)
  m.set({
    hour: 0,
    minute: 0,
    second: 0,
    millisecond: 0
  })
  const startWeekDate = m.week(moment().week()).startOf('week').valueOf();
  // //TODO addCard 函数系统时间多存了8小时 这个星期临时处理下
  // const startWeekDate = startWeek + 8 * 60 * 60 * 1000;
  const endWeekDate = m.week(moment().week()).endOf('week').valueOf();
  const _ = db.command
  let postCards = await db.collection('cards').where({
    _openid: card._openid,
    type: card.type,
    systemTime: _.lte(endWeekDate).and(_.gte(startWeekDate)),
  }).get()

  var totalTypePoint = 0
  for (var i = 0; i < postCards.data.length; i++) {
    let pCard = postCards.data[i]
    if (pCard.status == "checked") {
      console.log('checked')
      totalTypePoint += pCard.point
    }
  }
  console.log('postCards', postCards)
  console.log('totalTypePoint', totalTypePoint)
  card.point = calculatePoint(user.data[0], rules, card, totalTypePoint);

  console.log(card)

  await db.collection('cards').add({
    data: card,
    success: function (res) {
      id = res._id
      console.log(res)
    }
  })

  return {
    success: true,
    message: "打卡成功",
    data: {
      id: id
    }
  }
}

/**
 * 计算单项得分
 * 
 * @param {*} rules 
 * @param {*} card 
 */
function calculatePoint(user, rules, card, totalTypePoint) {
  var addPoint = 0
  if (card.type.index == 5) {
    return addPoint = card.point
  }

  for (var rule of rules.data) {
    if (rule.typeId == card.type.index) {
      switch (rule.typeId) {
        case 0:  // 跑步卡
          console.log(user.team)
          console.log("card.distance：" + card.distance)
          let distance = parseFloat(card.distance)
           if (distance >= 5.0 && distance < 10.0) {
            addPoint = 2
          } else if (distance >= 10.0 && distance < 15.0) {
            addPoint = 4
          } else if (distance >= 15.0 && distance < 20.0) {
            addPoint = 7
          }else if (distance >= 20.0) {
            addPoint = 10
          }else{
            addPoint = 0
          }
          
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 1: // 力量卡
          let time = parseFloat(card.time);
          if (time >= 30.0 && time < 60.0) {
            addPoint = 2;
          } else if (time >= 60.0 && time < 90.0) {
            addPoint = 4;
          } else if (time >= 90.0) {
            addPoint = 6
          } else addPoint = 0
          // addPoint = Math.floor(card.time / rule.measure * rule.point) + 1
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 2: // 越野卡（开启打卡-2024.10.7）
          let dis = parseFloat(card.distance) + parseFloat(card.altitude) / 100
          addPoint = Math.floor(dis / rule.measure * rule.point)
          if (dis >= 10.0 && dis < 20.0) {
            addPoint = 6
          } else if (dis >= 21 && dis < 30.0) {
            addPoint = 9
          } else if (dis >= 30) {
            addPoint = 11
          } else {
            addPoint = 0
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 3:// 跳绳卡
          console.log('rule.weekMaxPoint', rule.weekMaxPoint)
          addPoint = Math.floor(card.ropeNo / rule.measure * rule.point)
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 4:// 爬楼卡
          const level = parseFloat(card.level)
          if (level >= 100 && level < 200) {
            addPoint = 2
          } else if(level >= 200){
            addPoint = 4
          } else{
            addPoint = 0
          }
          // addPoint = Math.floor(card.level / rule.measure * rule.point)
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 7:
          const timeY = parseFloat(card.time)
          if (timeY >=30 && timeY < 60) {
            addPoint = 1
          } else if(timeY >= 60) {
            addPoint = 2
          } else {
            addPoint = 0
          }
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
      }
      console.log('rule.totalTypePoint', totalTypePoint)
      console.log('rule.addPoint', addPoint)
      console.log('rule.weekMaxPoint', rule.weekMaxPoint)
      break;
    }
  }
  console.log("addPoint", addPoint)
  return addPoint
}